<style>

</style>
<template>
  <canvas id="freq" style="width:100%; height:300px; "></canvas>
</template>
<script>
export default {
  name: 'freq',
  data () {
    return {

    }
  },
  mounted () {
    var tmp = this
    var canvas = document.getElementById('freq')
    var cwidth = canvas.width
    var cheight = canvas.height - 2
    var meterWidth = 10 // width of the meters in the spectrum
      // var gap = 2, // gap between meters
    var capHeight = 2
    var capStyle = '#fff'
    console.log(document.body.clientWidth)
    var meterNum = document.body.clientWidth / (10 + 2) // count of the meters
    var capYPositionArray = [] // //store the vertical position of hte caps for the preivous frame
    var ctx = canvas.getContext('2d')
    var gradient = ctx.createLinearGradient(0, 0, 0, 450)
    gradient.addColorStop(1, '#FF4258')
    gradient.addColorStop(0.5, '#FF4258')
    gradient.addColorStop(0, '#FF4258')

    // loop
    function renderFrame () {
      var array = new Uint8Array(window.analyser.frequencyBinCount)
      window.analyser.getByteFrequencyData(array)
      tmp.$store.commit('debug', array)
      var step = Math.round(array.length / meterNum) // sample limited data from the total array
      ctx.clearRect(0, 0, cwidth, cheight)
      for (var i = 0; i < meterNum; i++) {
        var value = array[i * step]
        if (capYPositionArray.length < Math.round(meterNum)) {
          capYPositionArray.push(value)
        };
        ctx.fillStyle = capStyle
            // draw the cap, with transition effect
        if (value < capYPositionArray[i]) {
          ctx.fillRect(i * 12, cheight - (--capYPositionArray[i]), meterWidth, capHeight)
        } else {
          ctx.fillRect(i * 12, cheight - value, meterWidth, capHeight)
          capYPositionArray[i] = value
        };
        ctx.fillStyle = gradient // set the filllStyle to gradient for a better look
        ctx.fillRect(i * 12 /* meterWidth+gap */, cheight - value + capHeight, meterWidth, cheight) // the meter
      }
      requestAnimationFrame(renderFrame)
    }
    renderFrame()
  }
}
</script>
